from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Union

import jwt
from passlib.context import CryptContext

from .config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") # 使用bcrypt算法创建hash器


ALGORITHM = "HS256"


def create_access_token(subject: Dict, expires_delta: timedelta) -> str:
    expire = datetime.now(timezone.utc) + expires_delta
    to_encode = {"exp": expire}
    to_encode.update(subject)
    encoded_jwt = jwt.encode(to_encode, settings.TOKEN_SIGN_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def decode_token(token: str) -> Dict:
    res: Dict = jwt.decode(
            token, settings.TOKEN_SIGN_KEY, algorithms=ALGORITHM
        )
    exp = res.get('exp', 0)
    now = datetime.now(timezone.utc)
    if exp < now:
        raise TimeoutError()
    return res


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码原文和hash后的密码是否一致

    Args:
        plain_password (str): 原密码
        hashed_password (str): hash后的

    Returns:
        bool: 结果
    """
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str: 
    """对密码进行hash

    Args:
        password (str): 密码

    Returns:
        str: hash结果
    """
    return pwd_context.hash(password)
